import { requestBookCategory } from "../util/request";

export async function searchBooks(query, categoryId = null) {
  try {
    // 获取分类数据
    const categoriesRes = await requestBookCategory();
    if (categoriesRes.code !== 200 || !categoriesRes.data) {
      throw new Error(categoriesRes.message || "获取分类数据失败");
    }

    // 深度优先遍历所有图书
    const matchedBooks = [];
    const traverseCategories = (categories) => {
      categories.forEach((category) => {
        // 检查分类是否匹配
        const isCategoryMatch = !categoryId || category.id === categoryId;

        // 处理子分类
        if (category.children && category.children.length) {
          traverseCategories(category.children);
        }

        // 处理当前分类的图书
        if (isCategoryMatch && category.books && category.books.length) {
          category.books.forEach((book) => {
            // 不区分大小写的模糊匹配
            const queryLower = query.toLowerCase();
            const titleMatch =
              book.title && book.title.toLowerCase().includes(queryLower);
            const isbnMatch = book.isbn && book.isbn.includes(query);

            if (titleMatch || isbnMatch) {
              matchedBooks.push(book);
            }
          });
        }
      });
    };

    traverseCategories(categoriesRes.data);

    return {
      code: 200,
      data: matchedBooks,
      message:
        matchedBooks.length > 0
          ? `找到 ${matchedBooks.length} 本图书`
          : "未找到匹配的图书",
    };
  } catch (error) {
    console.error("搜索出错:", error);
    return {
      code: 500,
      message: error.message,
      data: [],
    };
  }
}
